<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { fetchGoodsOderFrom, generateDeliveryOrder } from '@/api/goodsOderFrom'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import ViewOderForm from './components/ViewOderForm.vue'
import wsService from '@/utils/wsClient'

// 列表 & 分页
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
// 当前选中的订单详情弹窗
let dialogVisible = ref(false)
let deliveryOrderData = ref(null)

// 请求参数
const requestParams = ref({
  currentPage: 1,
  pageSize: 10,
  queryFields: {
    goodsName: '',
    dealerGoodsTypeName: '',
  },
})

// 成功发货后，刷新列表
const handleSuccessSend = () => {
  dialogVisible.value = false
  fetchOrderData()
}

// 获取数据
const fetchOrderData = async () => {
  try {
    loading.value = true
    const params = {
      ...requestParams.value,
      queryFields: {
        goodsName: requestParams.value.queryFields.goodsName.trim() || null,
        dealerGoodsTypeName: requestParams.value.queryFields.dealerGoodsTypeName.trim() || null,
      },
    }
    const res = await fetchGoodsOderFrom(params)
    if (res.success && res.data) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(res.msg || '获取商品订单失败')
    }
  } catch (error) {
    logger.error('获取商品订单失败', error)
    ElMessage.error('获取商品订单失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  requestParams.value.currentPage = 1
  fetchOrderData()
}

// 重置
const resetSearch = () => {
  requestParams.value.queryFields.goodsName = ''
  requestParams.value.queryFields.dealerGoodsTypeName = ''
  requestParams.value.currentPage = 1
  fetchOrderData()
}

// 详情
const handleViewDetails = async (row) => {
  try {
    const obj = {
      memberOrderMId: row.memberOrderMId,
      xzqhName: row.xzqhName,
      consignee: row.consignee,
      address: row.address,
      mobilphone: row.mobilphone,
      phone: row.phone,
      email: row.email,
      dealerId: row.dealerId,
      memberAddressId: row.memberAddressId,
      memberAddress: row.memberAddress,
    }
    const res = await generateDeliveryOrder(obj)
    if (res.success) {
      deliveryOrderData.value = res.data
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '生成发货单失败')
    }
  } catch (error) {
    logger.error('生成发货单失败', error)
    ElMessage.error('生成发货单失败')
  }
}

// 挂载
onMounted(() => {
  fetchOrderData()
  // 订阅 WebSocket 消息，命中相关提示时刷新列表
  wsService.addMessageListener(goodOrderMessageListener)
})

// 卸载
onUnmounted(() => {
  wsService.removeMessageListener(goodOrderMessageListener)
})

// 分页事件
const handleSizeChange = (val) => {
  requestParams.value.pageSize = val
  fetchOrderData()
}

const handleCurrentChange = (val) => {
  requestParams.value.currentPage = val
  fetchOrderData()
}

// WebSocket 消息监听：当有新的订单相关提示时刷新列表
const goodOrderMessageListener = (data) => {
  try {
    // data 可能为字符串或对象，仅处理对象的 tip 类提示
    if (!data || typeof data !== 'object') return
    const { msgType, msg = '', recordType } = data
    // 仅在提示型消息，且包含与订单发货/取消相关的关键词时刷新
    if (msgType === 'tip') {
      const text = String(msg)
      if (
        text.includes('订单') ||
        text.includes('发货') ||
        text.includes('取消') ||
        recordType === 'dealermsg01'
      ) {
        fetchOrderData()
      }
    }
  } catch (error) {
    logger.error('处理 WebSocket 消息失败', error)
  }
}
</script>
<template>
  <el-dialog v-model="dialogVisible" align-center destroy-on-close title="发货单详情" width="80%">
    <ViewOderForm
      :delivery-order="deliveryOrderData"
      v-if="deliveryOrderData"
      @success-send="handleSuccessSend"
    />
  </el-dialog>
  <div class="main-container">
    <div class="controller-container">
      <div class="controller-item">
        <el-form :inline="true" :model="requestParams.queryFields" @submit.prevent="handleSearch">
          <el-form-item label="商品名称">
            <el-input
              v-model="requestParams.queryFields.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="商品类别">
            <el-input
              v-model="requestParams.queryFields.dealerGoodsTypeName"
              placeholder="请输入商品类别"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><LineMdSearch /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <el-icon><LineMdSearch /></el-icon>
              </template>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <template #icon>
                <el-icon><LineMdClose /></el-icon>
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="table-container">
      <el-table v-loading="loading" :data="tableData" style="width: 100%" height="100%">
        <el-table-column
          prop="goodsName"
          show-overflow-tooltip
          label="商品名称"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            {{ row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="specifications" label="商品规格" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.specifications || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="purchaseQuantity" label="发货数量" min-width="100" align="center">
          <template #default="{ row }">
            {{ row.purchaseQuantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="库存数量" min-width="100" align="center">
          <template #default="{ row }">
            {{ row.quantity || 0 }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="商品单位" min-width="100" align="center">
          <template #default="{ row }">
            {{ row.unit || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dealerGoodsTypeName" label="商品类别" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.dealerGoodsTypeName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsPicture" label="商品封面图片" min-width="120" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.goodsPicture"
              :src="row.goodsPicture"
              style="width: 60px; height: 60px"
              fit="cover"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="商品产地" min-width="120" align="center">
          <template #default="{ row }">
            {{ row.address || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleViewDetails(row)">
              <template #icon>
                <el-icon><LineMdWatchLoop /></el-icon>
              </template>
              发货
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="requestParams.currentPage"
          v-model:page-size="requestParams.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;

  .controller-container {
    border-radius: 10px;
    background-color: #fff;

    .controller-item {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .table-container {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;
    overflow: hidden;
    gap: 10px;
    .el-table {
      flex: 1;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
